class Snake {
    // 蛇的整个dom元素
    snake: HTMLElement;

    // 蛇头dom元素
    head: HTMLElement;

    // 蛇身dom元素集合
    bodies: HTMLCollection;

    constructor() {
        this.head = document.querySelector('.snake > div') as HTMLElement;
        this.snake = document.getElementsByClassName('snake')[0] as HTMLElement;
        this.bodies = this.snake.getElementsByTagName('div');
    }
    // 蛇头的坐标
    get X() {
        return this.head.offsetLeft;
    }

    get Y() {
        return this.head.offsetTop;
    }

    // 设置蛇头移动，在移动前做相应的判断
    set X(value: number) {
        if (this.X === value) return
        this.check(value)
        this.head.style.left = value + 'px';
    }

    set Y(value: number) {
        if (this.Y === value) return
        this.check(value)
        this.head.style.top = value + 'px';
    }

    // 移动蛇身
    moveBody () {
        for(let i = this.bodies.length - 1; i > 0; i--) {
            let x = (this.bodies[i-1] as HTMLElement).offsetLeft;
            let y = (this.bodies[i-1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.top = y + 'px';
            (this.bodies[i] as HTMLElement).style.left = x + 'px';
        }
    }

    // 添加蛇身
    addBody() {
        const tempDiv = document.createElement("div");
        this.snake.insertAdjacentElement('beforeend', tempDiv);  
    }
    
    // 检测撞墙
    check(value: number) {
        if (value < 0 || value > 290) {
            throw new Error('蛇撞墙了！')
        }

    }

    // 判断蛇不可触碰自己的身体
    checkSelf() {
        for(let i = 1; i < this.bodies.length; i++) {
            if(this.X === (this.bodies[i] as HTMLElement).offsetLeft && this.Y === (this.bodies[i] as HTMLElement).offsetTop) {
                throw new Error('不可触碰自己身体！')
            }
        }
    }
}

export default Snake;

